package com.myc.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.myc.subject.common.enums.IsDeletedFlagCodeEnum;
import com.myc.subject.domain.convert.SubjectCategoryConverter;
import com.myc.subject.domain.entity.SubjectCategoryBO;
import com.myc.subject.domain.entity.SubjectLabelBO;
import com.myc.subject.domain.service.SubjectCategoryDomainService;
import com.myc.subject.domain.util.CacheUtil;
import com.myc.subject.infra.basic.entity.SubjectCategory;
import com.myc.subject.infra.basic.entity.SubjectLabel;
import com.myc.subject.infra.basic.entity.SubjectMapping;
import com.myc.subject.infra.basic.service.SubjectCategoryService;
import com.myc.subject.infra.basic.service.SubjectLabelService;
import com.myc.subject.infra.basic.service.SubjectMappingService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectCategoryDomainServiceImpl implements SubjectCategoryDomainService {

    @Autowired
    private SubjectCategoryService subjectCategoryService;

    @Resource
    private SubjectMappingService subjectMappingService;
    @Resource
    private SubjectLabelService subjectLabelService;

    @Resource
    private ThreadPoolExecutor labelThreadPool;

    @Resource
    private CacheUtil cacheUtil;

    public void add(SubjectCategoryBO subjectCategoryBO) {

        if(log.isInfoEnabled()){
            log.info("SubjectCategoryController.add.bo:{}", JSON.toJSONString(subjectCategoryBO));
        }
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagCodeEnum.UN_DELETED.getCode());
        subjectCategoryService.insert(subjectCategory);
    }

    /**
     * 查询一级分类列表
     * */
    public List<SubjectCategoryBO> queryCategory(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagCodeEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategories = subjectCategoryService.queryCategory(subjectCategory);
        List<SubjectCategoryBO> subjectCategoryBOS = SubjectCategoryConverter.INSTANCE.convertToCategoryBo(subjectCategories);
        if(log.isInfoEnabled()){
            log.info("SubjectCategoryDomainService.queryPrimartyCategory.bo:{}", JSON.toJSONString(subjectCategoryBOS));
        }
        //获取数量
        subjectCategoryBOS.forEach(subBo -> {
            Integer count = subjectCategoryService.querySubjectCount(subBo.getId());
            subBo.setCount(count);
        });
        return subjectCategoryBOS;
    }

    public Boolean update(SubjectCategoryBO subjectCategoryBO) {

        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        int count = subjectCategoryService.update(subjectCategory);
        return count>0;
    }

    public Boolean delete(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagCodeEnum.DELETED.getCode());
        int count = subjectCategoryService.update(subjectCategory);
        return count>0;
    }

    @SneakyThrows
    @Override
    public List<SubjectCategoryBO> queryCategoryAndLabel(SubjectCategoryBO subjectCategoryBO) {
        Long id = subjectCategoryBO.getId();
        //定义缓存并根据key查找本地是否有缓存
        String cacheKey= "categoryAndLabel." + subjectCategoryBO.getId();
        List subjectCategoryBOS = cacheUtil.getResult(cacheKey, SubjectCategoryBO.class, (key) -> getSubjectCategoryBOS(id));
        return subjectCategoryBOS;
    }

    private List<SubjectCategoryBO> getSubjectCategoryBOS(Long categoryId) {
        //获取当前一级分类下的所有二级分类
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(categoryId);
        subjectCategory.setIsDeleted(IsDeletedFlagCodeEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        if(log.isInfoEnabled()){
            log.info("SubjectCategoryDomainService.queryCategoryAndLabel.subjectCategoryList:{}", JSON.toJSONString(subjectCategoryList));
        }
        List<SubjectCategoryBO> categoryBOList = SubjectCategoryConverter.INSTANCE.convertToCategoryBo(subjectCategoryList);
//        //定义多线程列表处理分类标签
        //线程池并发处理，获取所有分类的标签信息
        Map<Long,List<SubjectLabelBO>> map = new HashMap<>();
        List<CompletableFuture<Map<Long, List<SubjectLabelBO>>>> completableFutureList =
                categoryBOList.stream().map(category -> (
                CompletableFuture.supplyAsync(() -> getLabelBOList(category), labelThreadPool))
        ).collect(Collectors.toList());
        //对结果进行处理,都放入map中
        completableFutureList.forEach(future->{
            try {
                Map<Long,List<SubjectLabelBO>> resultMap = future.get();
                if (!CollectionUtils.isEmpty(resultMap)){
                    map.putAll(resultMap);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        });
        //将map放入categoryBOList
        categoryBOList.forEach(categoryBO->{
            categoryBO.setLabelBOList(map.get(categoryBO.getId()));
        });
        return categoryBOList;
    }

    private Map<Long,List<SubjectLabelBO>> getLabelBOList(SubjectCategoryBO category) {
        Map<Long,List<SubjectLabelBO>> labelMap = new HashMap<>();
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setCategoryId(category.getId());
        List<SubjectMapping> subjectMappingList = subjectMappingService.queryLabelId(subjectMapping);
        if (CollectionUtils.isEmpty(subjectMappingList)){
            return null;
        }
        //获取subjectMappingList中的标签，放到列表中
        List<Long> labelIdList = subjectMappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        //根据labelId获取所有的List信息
        List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIdList);
        //构造subjectLabelBO的列表
        List<SubjectLabelBO> labelBOList = new LinkedList<>();
        labelList.forEach(label ->{
            SubjectLabelBO subjectLabelBO = new SubjectLabelBO();
            subjectLabelBO.setId(label.getId());
            subjectLabelBO.setLabelName(label.getLabelName());
            subjectLabelBO.setCategoryId(label.getCategoryId());
            subjectLabelBO.setSortNum(label.getSortNum());
            labelBOList.add(subjectLabelBO);
        });
        labelMap.put(category.getId(), labelBOList);
        return labelMap;
    }
}
